package main

import (
	"fmt"
	"log"
	"time"

	"gitee.com/wkkcool/self/nutsdb"
	"github.com/xujiajun/utils/strconv2"
	"github.com/xujiajun/utils/time2"
)

var (
	db     *nutsdb.DB
	bucket string
)

func init() {
	opt := nutsdb.DefaultOptions
	opt.RWMode = nutsdb.MMap
	opt.SyncEnable = false
	opt.Dir = "./"
	opt.EntryIdxMode = nutsdb.HintKeyAndRAMIdxMode
	// opt.EntryIdxMode = nutsdb.HintKeyValAndRAMIdxMode
	// opt.EntryIdxMode = nutsdb.HintBPTSparseIdxMode
	opt.SegmentSize = 1 * 1024 * 1024
	db, _ = nutsdb.Open(opt)
	bucket = "bucket1"
}

func main() {
	time2.Start()

	end := 1

	for j := 1; j <= end; j++ {
		fmt.Printf("key11=[%d]\n", j)
		if err := db.Update(
			func(tx *nutsdb.Tx) error {
				for i := 0; i < j*10000; i++ {
					key := []byte("body" + strconv2.IntToStr(i))
					val := []byte("valvalvavalvalvalvavalvalvalvavalvalvalvaval" + strconv2.IntToStr(i))
					fmt.Printf("key=[%q]\n", key)
					if err := tx.Put(bucket, key, val, 0); err != nil {
						return err
					}
				}
				// fmt.Printf("key12=[%d]\n", j)
				return nil
			}); err != nil {
			log.Fatal(err)
		}
		fmt.Println("")
		if err := db.Update(
			func(tx *nutsdb.Tx) error {
				for i := 10000; i < 20000; i++ {
					key := []byte("body" + strconv2.IntToStr(i))
					val := []byte("valvalvavalvalvalvavalvalvalvavalvalvalvaval" + strconv2.IntToStr(i))
					fmt.Printf("key=[%q]\n", key)
					if err := tx.Put(bucket, key, val, 2); err != nil {
						return err
					}
				}
				// fmt.Printf("key12=[%d]\n", j)
				return nil
			}); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("key11=[%d]\n", j)
	}
	fmt.Printf("key13=[%d]\n", 3)
	fmt.Println("batch put data cost: ", time2.End())
	time.Sleep(time.Second * 4)
	db.Merge()
	// db.Backup()
	for j := 1; j <= end; j++ {
		if err := db.View(
			func(tx *nutsdb.Tx) error {
				for i := (j - 1) * 10000; i < j*10000; i++ {
					key := []byte("body" + strconv2.IntToStr(i))
					// val := []byte("valvalvavalvalvalvavalvalvalvavalvalvalvaval" + strconv2.IntToStr(i))
					// fmt.Printf("key=[%q]\n", key)
					e, err := tx.Get(bucket, key)
					if err != nil {
						// if _, err := tx.Compare(bucket, key,val); err != nil{
						return err
					}
					fmt.Printf("value=[%q]\n", e.Value)
				}
				fmt.Printf("key12=[%d]\n", j)
				return nil
			}); err != nil {
			log.Fatal(err)
		}
	}
	defer db.Close()
	return
}
